package com.raysun.androidbase.intent

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.AlarmClock
import android.provider.CalendarContract
import android.provider.ContactsContract
import android.provider.ContactsContract.Contacts
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.raysun.androidbase.databinding.ActivityIntentSummaryBinding
import com.raysun.androidbase.intent.extension.PickSpecificContactContract
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.Calendar

@Suppress("unused")
const val ACTION_DETECT = "com.raysun.androidbase.action.ACTION_DETECT"

@Suppress("unused")
const val EXTRA_DETECT = "com.raysun.androidbase.EXTRA_DETECT"

class IntentSummaryActivity : AppCompatActivity() {

    private lateinit var binding: ActivityIntentSummaryBinding

    private var contactUri: Uri? = null

    @Suppress("unused")
    private val commonIntentLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it?.resultCode != Activity.RESULT_OK) {
                Toast.makeText(applicationContext, "操作失败", Toast.LENGTH_SHORT).show()
                return@registerForActivityResult
            }
            when (it.data?.action) {
                Intent.ACTION_PICK -> {

                }

                else -> {

                }
            }
        }

    private val takePictureLauncher =
        registerForActivityResult(ActivityResultContracts.TakePicture()) { isSuccessful ->
            Log.d("Raysunshine", "TakePicture: $isSuccessful")
        }

    private val takeVideoLauncher =
        registerForActivityResult(ActivityResultContracts.CaptureVideo()) { isSuccessful ->
            Log.d("Raysunshine", "CaptureVideo: $isSuccessful")
        }

    private val pickContactLauncher =
        registerForActivityResult(ActivityResultContracts.PickContact()) { nullableUri ->
            nullableUri?.let {
                contactUri = it
                contentResolver.query(it, null, null, null, null).use { cursor ->
                    if (cursor?.moveToFirst() == true) {
                        val displayColumIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME)
                        val displayName = cursor.getString(displayColumIndex)
                        Log.d("Raysunshine", "pickContact: $displayName")
                    }
                }
            }
        }

    private val readContactPermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
            if (isGranted) {
                pickContactLauncher.launch(null)
            }
        }

    private val readSpecificContactLauncher =
        registerForActivityResult(PickSpecificContactContract()) {
            it?.let {
                val projection = arrayOf(ContactsContract.CommonDataKinds.Phone.NUMBER)
                contentResolver.query(it, projection, null, null, null).use { cursor ->
                    if (cursor?.moveToFirst() == true) {
                        val phoneNumberIndex =
                            cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
                        val number = cursor.getString(phoneNumberIndex)
                        Log.d("Raysunshine", "pickSpecificContact: $number")
                    }
                }
            }
        }

    private val getMultipleContents =
        registerForActivityResult(ActivityResultContracts.GetMultipleContents()) {
            it?.forEachIndexed { index, uri ->
                contentResolver.openFileDescriptor(uri, "r")?.use { descriptor ->
                    val fis = FileInputStream(descriptor.fileDescriptor)
                    val bis = BufferedInputStream(fis)
                    val filesDir = getExternalFilesDir("")
                    val file = File(filesDir, "ss$index.jpg")
                    val fos = FileOutputStream(file)
                    val bos = BufferedOutputStream(fos)
                    bis.copyTo(bos)
                }
            }
        }

    private val callPhonePermissionLauncher =
        registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
            if (isGranted) {
                val intent = Intent(Intent.ACTION_CALL).apply {
                    data = Uri.parse("tel:13965309426")
                }
                if (intent.resolveActivity(packageManager) != null) {
                    startActivity(intent)
                }
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityIntentSummaryBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.createAlarm.setOnClickListener {
            val intent = Intent(AlarmClock.ACTION_SET_ALARM).apply {
                putExtra(AlarmClock.EXTRA_MESSAGE, "message")
                putExtra(AlarmClock.EXTRA_HOUR, 7)
                putExtra(AlarmClock.EXTRA_MINUTES, 30)
                putExtra(AlarmClock.EXTRA_DAYS, arrayListOf(Calendar.MONDAY, Calendar.THURSDAY))
                putExtra(AlarmClock.EXTRA_VIBRATE, true)
                putExtra(AlarmClock.EXTRA_SKIP_UI, false)
            }
            if (intent.resolveActivity(packageManager) != null) {
                startActivity(intent)
            }
        }

        binding.createTimer.setOnClickListener {
            val intent = Intent(AlarmClock.ACTION_SET_TIMER).apply {
                putExtra(AlarmClock.EXTRA_LENGTH, 30) // seconds
                putExtra(AlarmClock.EXTRA_MESSAGE, "message")
                putExtra(AlarmClock.EXTRA_SKIP_UI, false)
            }
            if (intent.resolveActivity(packageManager) != null) {
                startActivity(intent)
            }

        }

        binding.showAlarms.setOnClickListener {
            Intent(AlarmClock.ACTION_SHOW_ALARMS).let {
                if (it.resolveActivity(packageManager) != null) {
                    startActivity(it)
                }
            }
        }

        binding.createCalendarEvent.setOnClickListener {
            val intent = Intent(Intent.ACTION_INSERT).apply {
                putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true)
                putExtra(CalendarContract.Events.TITLE, "good day")
                putExtra(CalendarContract.Events.EVENT_LOCATION, "Nan Jing")
                data = CalendarContract.Events.CONTENT_URI
            }
            if (intent.resolveActivity(packageManager) != null) {
                startActivity(intent)
            }
        }

        binding.takePicture.setOnClickListener {
            val file = File(getExternalFilesDir(""), "target1.jpg")
            val uri = FileProvider.getUriForFile(
                applicationContext,
                applicationContext.packageName,
                file
            )
            takePictureLauncher.launch(uri)
        }

        binding.takeVideo.setOnClickListener {
            val file = File(getExternalFilesDir(""), "target.mp3")
            val uri = FileProvider.getUriForFile(
                applicationContext,
                applicationContext.packageName,
                file
            )
            takeVideoLauncher.launch(uri)
        }

        binding.staticTakePicture.setOnClickListener {
            val intent = Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA)
            if (intent.resolveActivity(packageManager) != null) {
                startActivity(intent)
            }
        }

        binding.pickContact.setOnClickListener {
            checkSinglePermission(
                Manifest.permission.READ_CONTACTS,
                onGranted = {
                    pickContactLauncher.launch(null)
                },
                shouldShowRationale = {
                    Toast.makeText(
                        applicationContext,
                        "获取联系人信息权限用于测试选择联系人功能",
                        Toast.LENGTH_LONG
                    ).show()
                },
                onOtherCase = {
                    readContactPermissionLauncher.launch(Manifest.permission.READ_CONTACTS)
                }
            )
        }

        binding.pickSpecificContact.setOnClickListener {
            readSpecificContactLauncher.launch(null)
        }

        binding.viewContact.setOnClickListener {
            contactUri?.let {
                val intent = Intent(Intent.ACTION_VIEW, it)
                if (intent.resolveActivity(packageManager) != null) {
                    startActivity(intent)
                }
            } ?: runOnUiThread {
                Toast.makeText(applicationContext, "请先选择一个联系人", Toast.LENGTH_LONG).show()
            }
        }

        binding.editContact.setOnClickListener {
            contactUri?.let {
                val intent = Intent(Intent.ACTION_EDIT, it).apply {
                    putExtra(ContactsContract.Intents.Insert.EMAIL, "1950546998@qq.com")
                }
                if (intent.resolveActivity(packageManager) != null) {
                    startActivity(intent)
                }
            } ?: runOnUiThread {
                Toast.makeText(applicationContext, "请先选择一个联系人", Toast.LENGTH_LONG).show()
            }
        }

        binding.insertContact.setOnClickListener {
            val intent = Intent(Intent.ACTION_INSERT).apply {
                type = Contacts.CONTENT_TYPE
                putExtra(ContactsContract.Intents.Insert.NAME, "Raysunshine")
                putExtra(ContactsContract.Intents.Insert.PHONE, "13965309426")
                putExtra(ContactsContract.Intents.Insert.EMAIL, "1950546998@qq.com")
            }
            if (intent.resolveActivity(packageManager) != null) {
                startActivity(intent)
            }
        }

        binding.getMultipleContents.setOnClickListener {
            getMultipleContents.launch("image/*")
        }

        binding.makeDial.setOnClickListener {
            val intent = Intent(Intent.ACTION_DIAL).apply {
                data = Uri.parse("tel:13965309426")
            }
            if (intent.resolveActivity(packageManager) != null) {
                startActivity(intent)
            }
        }

        binding.makeCall.setOnClickListener {
            checkSinglePermission(
                Manifest.permission.CALL_PHONE,
                onGranted = {
                    val intent = Intent(Intent.ACTION_CALL).apply {
                        data = Uri.parse("tel:13965309426")
                    }
                    if (intent.resolveActivity(packageManager) != null) {
                        startActivity(intent)
                    }
                },
                shouldShowRationale = {
                    Toast.makeText(
                        applicationContext,
                        "请授予我们拨打电话的权限，我们需要用于测试拨打电话功能",
                        Toast.LENGTH_LONG
                    ).show()
                },
                onOtherCase = {
                    callPhonePermissionLauncher.launch(Manifest.permission.CALL_PHONE)
                }
            )
        }

        binding.openSetting.setOnClickListener {
            val intent =
                Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                    data = Uri.parse("package:${applicationContext.packageName}")
                }
            if (intent.resolveActivity(packageManager) != null) {
                startActivity(intent)
            }
        }


        binding.sendMessage.setOnClickListener {
            val intent = Intent(Intent.ACTION_SENDTO).apply {
                data = Uri.parse("smsto:13965309426") // this ensure only SMS apps respond
                putExtra("sms_body", "你好呀，这是我的一封短信")
            }
            if (intent.resolveActivity(packageManager) != null) {
                val chooser = Intent.createChooser(intent, "")
                startActivity(chooser)
            }
        }
    }

    private fun checkSinglePermission(
        permission: String,
        onGranted: () -> Unit,
        shouldShowRationale: () -> Unit,
        onOtherCase: () -> Unit,
    ) {
        when {
            ContextCompat.checkSelfPermission(
                applicationContext,
                permission
            ) == PackageManager.PERMISSION_GRANTED -> onGranted()

            ActivityCompat.shouldShowRequestPermissionRationale(
                this@IntentSummaryActivity,
                permission
            ) -> shouldShowRationale()

            else -> onOtherCase()
        }
    }
}

